package com.meirengu.channel.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.meirengu.channel.service.HouBankService;
import com.meirengu.utils.Base64Utils;
import com.meirengu.utils.EncodeUtil;
import com.meirengu.utils.HttpClientInvoker;
import com.meirengu.webview.common.Constants;
import com.meirengu.webview.model.KwThirdback;
import com.meirengu.webview.service.KwThirdbackService;
import com.meirengu.webview.utils.ConfigUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by root on 2018-01-02.
 */
@Service
public class HouBankServiceImpl implements HouBankService {

    Logger logger = LoggerFactory.getLogger(HouBankServiceImpl.class);

    @Autowired
    KwThirdbackService kwThirdbackService;

    public Integer applyLoan(String importIndex, String name, String phone, String birthday, int incoming,
                             String cardType, String cardNo, String city,
                             String professionType, String incomeRange, String incomeType,
                             String isCreditRecord, String isWelfare, String isHousingFund,
                             String isHasCar, String isCarLoan, String isHasHouse,
                             String isInsurance, String flowNo, String custSex,
                             String marriage, String eduExperience, String applyTerm,
                             String applySum, String isAtom) {
        String frontUrl = ConfigUtil.getConfig("front.url");
        String url = null;
        String params = null;
        BASE64Encoder base64Encoder = new BASE64Encoder();
        BASE64Decoder base64Decoder = new BASE64Decoder();

        try {

            url = Base64Utils.encodeBuffer(ConfigUtil.getConfig("import.url"), "utf-8");

            byte[] key = Base64Utils.base64ToByteArray("yhdjZGfcsd56fdtsbW5vcHFyc3R1ldx4".trim());
            JSONObject jsonData = new JSONObject();
            jsonData.put("supplierCode", "38");//供应商ID
            jsonData.put("importIndex", importIndex);//导入的批次号


            JSONObject userJson = new JSONObject();
            userJson.put("rowIndex", null);//导入成功的行数ID
            userJson.put("supplierCodeSub", null);//导入的媒体细分
            userJson.put("name", name);//导入客户的姓名(必填)
            userJson.put("phone", phone);//导入客户的手机号码(必填)
            userJson.put("birthday", birthday);//导入客户的生日
            userJson.put("incoming", incoming);//导入客户的收入
            userJson.put("cardType", null);//证件类型
            userJson.put("cardNo", null);//证件号码

            String cityCode = ConfigUtil.getConfig("H" + city);
            userJson.put("cityCode", cityCode);//导入客户所在城市编码(必填)
            userJson.put("professionType", professionType);//1-上班，2-企业主，3-公务员，4-个体户，5-自由职业者
            userJson.put("incomeRange", incomeRange);//4-2000以下，3-200至5000,2-5000至10000,1-10000以上
            userJson.put("incomeType", incomeType);//1-银行卡打款,2-现金发放,3-混合,4其他
            userJson.put("isCreditRecord", isCreditRecord);//信用记录：（是/否）1-有,2-没有
            userJson.put("isWelfare", isWelfare);//是否缴纳社保：有/无 1-有,2-没有
            userJson.put("isHousingFund", isHousingFund);//是否缴纳公积金：有/无 1-有,2-没有
            userJson.put("isHasCar", isHasCar);//是是否有车：有/无 1-有,2-没有
            userJson.put("isCarLoan", isCarLoan);//购车形式 1-全款购车 2-分期贷款已还清 3-分期贷款还款中
            userJson.put("isHasHouse", isHasHouse);
            userJson.put("isInsurance", isInsurance);//是否有寿险保单：有/无 1-有,2-没有
            userJson.put("flowNo", null);//期望贷款产品：信用贷/抵押贷  PA0100-信用贷;PA0200-抵押贷
            userJson.put("custSex", custSex);//性别： 男/女  01-男，02-女
            userJson.put("marriage", null);//婚姻状况: 10-未婚,20-已婚有子女,21-已婚无子女，23-离异，30-其他
            userJson.put("eduExperience", null);//学历： 5-高中以下；4-中专/技校/高中；3-大专；2-本科；1-硕士及以上
            userJson.put("applyTerm", null);//申请贷款期限：备注例如：1,6,12
            userJson.put("applySum", applySum);//期望贷款金额：备注 长度判断（太长了会截取前面12个字
            userJson.put("isAtom", null);//该导入的名单是否用做微粒贷的标志 1表示导入的该名单可以用做微粒贷 0表示该导入的名单不用做微粒贷
            JSONArray importListJson = new JSONArray();
            importListJson.add(userJson);
            jsonData.put("importList", importListJson);

//            String sendStr = "{'supplierCode':'38','importIndex':'c0e8d3bdee9d11e7a9c294e979547408','importList':["
//                    + "{'supplierCodeSub':'MKT-YUWEN-2016','name':'毛毛毛', 'phone':'15835132986','birthday':'1981-07-07','incoming':'3500',"
//                    + "'cardType':'01','cardNo':'610581198107072537','cityCode':'2729','professionType':'3','incomeRange':'3','incomeType':'1',"
//                    + "'isCreditRecord':'1','isWelfare':'1','isHasCar':'1','isCarLoan':'2','isHasHouse':'2','custSex':'1','applyTerm':'12','applySum':'10000'}]}";

            String sendStr = jsonData.toString();

            byte[] sendByte = EncodeUtil.des3EncodeECB(key, sendStr.getBytes("utf-8"));

            String encryptStr = base64Encoder.encodeBuffer(sendByte);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("sendData", encryptStr);

            Map<String, Object> requestParams = new HashMap<String, Object>();
            requestParams.put("params", Base64Utils.encodeBuffer(jsonObject.toString(), "utf-8"));
            requestParams.put("url", url);
            requestParams.put("method", "post");
            requestParams.put("posttype", "HTTPCLIENT");//在前置添加HTTPCLIENT转发方式
            requestParams.put("charcode", "utf-8");

            //接口调用信息表
            KwThirdback thirdback = new KwThirdback();
            thirdback.setInterfaceCode("houbank-import");
            thirdback.setInterfaceName("厚本金融-导入接口");
            thirdback.setMobile(phone);
            thirdback.setSendUrl(frontUrl.toString());
            thirdback.setParams(sendStr);
            thirdback.setCode(Constants.BUSINESS_STATUS_FAIL);

            try {
                HttpClientInvoker httpInvoker = HttpClientInvoker.getInstance();
                String callRst = httpInvoker.invoke(frontUrl, requestParams, true);//使用前置转发
                String returnStr = Base64Utils.decodeBuffer(callRst, "utf-8");

                logger.info("==HouBankServiceImpl.applyLoan request success. result");

                /**
                 * 解外层包，把returnData解压出来
                 */
                JSONObject returnObject = new JSONObject();
                returnObject = JSON.parseObject(returnStr);
                String payload = returnObject.get("returnData").toString();
                byte[] returnByte = base64Decoder.decodeBuffer(payload);
                byte[] decryptByte = EncodeUtil.ees3DecodeECB(key, returnByte);
                String decryptStr = new String(decryptByte, "UTF-8");

                thirdback.setBackUrl(callRst);
                thirdback.setHttpCode(200);
                thirdback.setHttpContent(decryptStr);

                JSONObject rObject = new JSONObject();
                rObject = JSON.parseObject(decryptStr);
                String rCode = rObject.getString("returnCode");
                String rMsg = rObject.getString("returnMsg");
                if ("0000".equals(rCode)) {
                    thirdback.setCode(Constants.BUSINESS_STATUS_SUCCESS);
                    thirdback.setMessage("成功");
                    logger.info("==HouBankServiceImpl.applyLoan business success");
                } else if ("0002".equals(rCode) || "0003".equals(rCode)) {
                    thirdback.setCode(Constants.BUSINESS_STATUS_REPEAT);
                    thirdback.setMessage(rCode + ":" + rMsg);
                    logger.warn("==HouBankServiceImpl.applyLoan business fail");
                } else {
                    thirdback.setCode(Constants.BUSINESS_STATUS_FAIL);
                    thirdback.setMessage(rCode + ":" + rMsg);
                    logger.warn("==HouBankServiceImpl.applyLoan business fail");
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(ExceptionUtils.getFullStackTrace(e));
                thirdback.setHttpCode(408);
                logger.warn("==HouBankServiceImpl.applyLoan request fail. code:, result:");
            } finally {
                kwThirdbackService.insert(thirdback);
                return thirdback.getCode();
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
        }
        return 0;
    }
}

